package cn.itsource.basic.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.itsource.config.exception.BusinessException;
import cn.itsource.org.vo.LoginVo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取redis的登录信息
 */
public class GetRedisLoginVoUtil {

    //获取登录用户的id信息
    public static Long getUserId(){
        return getLoginUserByRedis().getUserId();
    }
    //获取登录用户的店铺id信息
    public static Long getShopId(){
        Long shopId = getLoginUserByRedis().getShopId();
        if (shopId == null){
            throw new BusinessException("您不属于店铺员工，请去面试");
        }
        return shopId;
    }

    public static LoginVo getLoginUserByRedis(){
        //1.获取request对象,拿到请求头中携带的token信息
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");

        //2.通过工具注入redis对象（spring对象）
        RedisService redisService = SpringUtil.getBean(RedisService.class);
        //3.从redis中获取用户信息
        LoginVo loginVo = redisService.getKeyObjectValue(token, LoginVo.class);

        return loginVo;
    }

}
